from datetime import datetime
from django.shortcuts import redirect
from django.utils.deprecation import MiddlewareMixin
from django.conf import settings
from web import models

class Tracer(object):
    def __init__(self) -> None:
       self.user=None
       self.price_policy=None 
       self.project=None

class AuthMiddleware(MiddlewareMixin):
    def process_request(self,request):
        id = request.session.get('id',0)
        user_obj = models.UserInfo.objects.filter(id=id).first()
        request.tracer = Tracer()
        request.tracer.user = user_obj 
        # print(request.path_info)    
        if request.path_info in settings.WHITE_REGEX_URL_LIST:
            return
        else:
            # tracer_existed = getattr(request, 'tracer', False)
            # if not tracer_existed:
            if not request.tracer.user:
                return redirect('/web/login')
           
            now_time = datetime.now() 
            _obj = models.Transaction.objects.filter(user=request.tracer.user,status=2).order_by('-id').first() 
            if _obj.end_datetime and _obj.end_datetime<now_time:
                _obj = models.PricePolicy.objects.filter(category=1, title='个人免费版').first()
                #当前记录未过期
            request.tracer.price_policy = _obj.price_policy
            
    def process_view(self, request, callback, callback_args, callback_kwargs):
        
        if not request.path_info.startswith('/web/manage/'):
            # 非项目相关，不理会
            return
        
        # 路由匹配后获得的参数，包含project id
        project_id = callback_kwargs.get('project_id')
        # 判断project_id是否是自己创建或参与的
         
        proj_obj = models.Project.objects.filter(creator=request.tracer.user, id=project_id).first()
        if proj_obj:
            request.tracer.project = proj_obj
            return
        
        proj_user_obj = models.ProjectUser.objects.filter(project_id=project_id,user=request.tracer.user).first()
        if proj_user_obj:
            request.tracer.project = proj_user_obj.project
            return
        
        #禁止访问
        return redirect('/web/project/list')    